package com.oa.organization.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.oa.entity.ExtMsgResult;
import com.oa.entity.Result;
import com.oa.log.annotation.Log;
import com.oa.organization.dto.OrganizationDto;
import com.oa.organization.dto.OrganizationPieDto;
import com.oa.organization.entity.OrganizationTree;
import com.oa.organization.service.OrganizationService;

@RestController
@RequestMapping("/organization")
public class OrganizationController {
	@Resource
	private OrganizationService organizationService;

	// organization/allOrganization 获取组织部门结构
	@GetMapping("/allOrganization")
	public Result<Iterable<OrganizationDto>> findAllOrganization() {
		return new Result<>(200, "获取组织结构", organizationService.findAllOrganization());
	}

	// organization/organizationPie 获取组织部门占比信息
	@GetMapping("/organizationPie")
	public Result<Iterable<OrganizationPieDto>> getOrganizationPie() {
		return new Result<>(200, "组织部门占比圆饼图信息", organizationService.getOrganizationPie());
	}

	// organization/findNodes 获取组织部门节点
	@GetMapping("/findNodes")
	public List<OrganizationTree> findNodesByParentId(String node) {
		if (node.equals("root")) {
			return organizationService.findNodes(null);
		} else {
			return organizationService.findNodes(Long.parseLong(node));
		}
	}

	// organization/saveOrUpdateOrganization 增加或更新部门
	@PostMapping("/saveOrUpdateOrganization")
	@Log(oprate = "增加或更新部门")
	@PreAuthorize("hasAuthority('ADMIN')")
	public ExtMsgResult saveOrUpdateOrganization(OrganizationDto organizationDto) {
		try {
			organizationService.saveOrUpdateOrganization(organizationDto);
			return new ExtMsgResult(200, "保存成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new ExtMsgResult(400, "保存失败");
		}
	}

	// organization/deleteOrganization 删除部门
	@PostMapping("/deleteOrganization")
	@Log(oprate = "删除部门")
	@PreAuthorize("hasAuthority('ADMIN')")
	public ExtMsgResult deleteOrganization(Long id) {
		try {
			organizationService.deleteOrganization(id);
			return new ExtMsgResult(200, "删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new ExtMsgResult(400, "删除失败");
		}
	}

}
